package com.yuanfeng.payment.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.yuanfeng.commoms.config.WXPayConfig;
import com.yuanfeng.commoms.config.YFConfig;
import com.yuanfeng.commoms.constant.CommonType;
import com.yuanfeng.commoms.dto.base.MemberMessageListIntegralDTO;
import com.yuanfeng.commoms.dto.oos.OssUploadUpdateParamDTO;
import com.yuanfeng.commoms.dto.order.WapGoodsSaleSumDTO;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.*;
import com.yuanfeng.commoms.util.Json.JsonUtils;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import com.yuanfeng.payment.dto.PayConsumeRecordDTO;
import com.yuanfeng.payment.dto.QueryGoodsParaDTO;
import com.yuanfeng.payment.dto.QueryRecordParaDTO;
import com.yuanfeng.payment.feign.GoodServiceClient;
import com.yuanfeng.payment.feign.OrderServiceClient;
import com.yuanfeng.payment.feign.ThirdPartyServiceClient;
import com.yuanfeng.payment.feign.UsermsServiceClient;
import com.yuanfeng.payment.mapper.PayConfigMapper;
import com.yuanfeng.payment.mapper.PayConsumeRecordMapper;
import com.yuanfeng.payment.mapper.PayConsumeTradeMapper;
import com.yuanfeng.payment.mapper.PayUserResourceMapper;
import com.yuanfeng.payment.service.WeChatPayServices;
import io.seata.core.context.RootContext;
import io.seata.core.exception.TransactionException;
import io.seata.spring.annotation.GlobalTransactional;
import io.seata.tm.api.GlobalTransactionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class WeChatPayServicesImpl implements WeChatPayServices {

    final static Logger log = LoggerFactory.getLogger(WeChatPayServicesImpl.class);

    @Resource
    private PayConfigMapper payConfigMapper;

    @Autowired
    private OrderServiceClient orderServiceClient;

    @Resource
    private PayUserResourceMapper payUserResourceMapper;

    @Autowired
    private GoodServiceClient goodServiceClient;

    @Autowired
    private UsermsServiceClient usermsServiceClient;

    @Autowired
    private ThirdPartyServiceClient thirdPartyServiceClient;

    @Resource
    private PayConsumeTradeMapper payConsumeTradeMapper;

    @Resource
    private PayConsumeRecordMapper payConsumeRecordMapper;

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public String notifyWeiXinPay(HttpServletRequest request, HttpServletResponse response) {
        log.info("------支付成功，进入回调notifyWeiXinPay------");
        try {
            InputStream inStream = request.getInputStream();
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            String resultxml = outSteam.toString("utf-8");
            log.info("resultxml:" + resultxml);
            @SuppressWarnings("unchecked")
            Map<String, String> params = PayCommonUtil.doXMLParse(resultxml);
            outSteam.close();
            inStream.close();
            Map<String, String> return_data = new HashMap<String, String>();
            if (!PayCommonUtil.isTenpaySign(params)) {
                // 支付失败
                log.info("------支付失败------");
                return_data.put("return_code", "FAIL");
                return_data.put("return_msg", "return_code不正确");
                log.info("return_data：" + StringUtils.GetMapToXML(return_data));
                return StringUtils.GetMapToXML(return_data);
            } else {
                log.info("===============付款成功==============");
                String out_trade_no = params.get("out_trade_no");
                log.info("-----out_trade_no-----" + out_trade_no);
                // 获取wx传来的订单价格
                String total_fee = params.get("total_fee");
                log.info("-----total_fee-----" + total_fee);
                // 微信支付分配的商户号
                String mch_id = params.get("mch_id");
                log.info("-----mch_id-----" + mch_id);
                // 微信支付订单号
                String transaction_id = params.get("transaction_id");
                log.info("-----transaction_id-----" + transaction_id);
                // 更改销量
                List<WapGoodsSaleSumDTO> wapGood = payUserResourceMapper.queryGoodsByOrderId(out_trade_no);
                goodServiceClient.updateGoodsSalenum(wapGood);
                Map<String, String> orderIdIsNum = new HashMap<>();
                //虚拟订单 0是 1否
                Integer virtualGoods = null;
                //门店订单 1 是 2否
                Integer orderIsShopTake = null;
                // 判断纯数字订单，实际支付订单
                if (PayToolUtil.isInteger(out_trade_no)) {
                    QueryRecordParaDTO queryGoodsPara = payConsumeTradeMapper.queryRecordPriceAndName(out_trade_no);

                    if (null != queryGoodsPara && !queryGoodsPara.getOrderStateId().equals(6)) {
                        String orderId = queryGoodsPara.getOrderId();
                        String recordMoney = PayToolUtil.getMoney(queryGoodsPara.getTradePaymentAmount());
                        if (out_trade_no.equals(orderId) && total_fee.equals(recordMoney)
                                && mch_id.equals(WXPayConfig.MCH_ID)) {
                            log.info("----判断成功----");
                            payConsumeTradeMapper.updateConsumeTradePaymentMoney(out_trade_no, 3);
                            orderIdIsNum.put("orderId", out_trade_no);
                            //订单号是数字
                            orderIdIsNum.put("isNum", "0");
                            //判断是否是积分商品订单 扣除积分
                            updateUserJIfen(out_trade_no);
                            //判断是否是虚拟订单
                            Map<String, Integer> judgeOrderMap = this.virtualWxExchangeCode(orderIdIsNum);
                            virtualGoods = judgeOrderMap.get("virtualGoods");
                            orderIsShopTake = judgeOrderMap.get("orderIsShopTake");
                            Map<Object, Object> map = new HashMap<Object, Object>();
                            Integer payCode = 3;
                            // 待发货
                            Integer orderStatus = 3;
                            //门店订单 0 是 1 否
                            if (null != orderIsShopTake && 1 == orderIsShopTake) {
                                //如果是门店订单就将订单状态修改为 已发货
                                orderStatus = 4;
                            }
                            //虚拟订单 0 是 1 否
                            if (null != virtualGoods && 0 == virtualGoods) {
                                //如果是虚拟订单就将订单状态修改为 已发货
                                orderStatus = 4;
                            }
                            // 支付方式
                            Integer paymentId = 1;
                            // 支付方式名称
                            String paymentName = "在线支付";
                            // 支付时间
                            String paymentTime = DateUtils.getTime();
                            // 第三方支付号
                            String paymentOtherNumber = transaction_id;
                            String orderFrom = RedisUtil.get(YFConfig.FKGOU_ORDERFORM + out_trade_no);
                            map.put("payCode", payCode);
                            map.put("orderFrom", orderFrom);
                            map.put("paymentId", paymentId);
                            // 商户订单号
                            map.put("paymentNumber", out_trade_no);
                            map.put("orderStatus", orderStatus);
                            map.put("paymentName", paymentName);
                            map.put("paymentTime", paymentTime);
                            map.put("paymentOtherNumber", paymentOtherNumber);
                            boolean a = orderServiceClient.HFiveUpdateOrderBaseByPayment(map);
                            // 更改支付表状态ConsumeRecord
                            Integer recordStatus = 3;
                            Map<String, Object> recordMap = new HashMap<>();
                            recordMap.put("recordStatus", recordStatus);
                            recordMap.put("paymentTime", paymentTime);
                            recordMap.put("outTradeNo", out_trade_no);
                            boolean updateConsumeRecord = payConsumeRecordMapper.updateComsumeRecordByPureDigital(recordMap);
                            // 更改ConsumeTrade
                            Integer orderStateId = 3;
                            // 支付方式
                            Integer paymentChannelId = 4;
                            String closeTime = DateUtils.getTime();
                            boolean updateConsumeTrade = payConsumeTradeMapper.updateConsumeTradeByPureDigital(orderStateId,
                                    paymentTime, closeTime, out_trade_no, paymentChannelId);

                            // 发送feign,提交下单通知
                            Map<String, Object> messageMap = new HashMap<String, Object>();
                            // 支付号
                            messageMap.put("orderId", out_trade_no);
                            messageMap.put("paymentTime", paymentTime);
                            // 发送下单通知
                            orderServiceClient.orderToInform(messageMap);
                            return_data.put("return_code", "SUCCESS");
                            return_data.put("return_msg", "OK");
                            return StringUtils.GetMapToXML(return_data);
                        } else {
                            log.info("订单号或订单金额不符！");
                            return_data.put("return_code", "FAIL");
                            return_data.put("return_msg", "订单号或订单金额不符！");
                            return StringUtils.GetMapToXML(return_data);
                        }
                    } else {
                        return_data.put("return_code", "SUCCESS");
                        return_data.put("return_msg", "OK");
                        return StringUtils.GetMapToXML(return_data);
                    }
                } else {
                    orderIdIsNum.put("orderId", out_trade_no);
                    //订单号不是数字
                    orderIdIsNum.put("isNum", "1");
                    //判断是否是虚拟订单
                    Map<String, Integer> judgeOrderMap = this.virtualWxExchangeCode(orderIdIsNum);
                    virtualGoods = judgeOrderMap.get("virtualGoods");
                    // 支付订单号
                    orderIsShopTake = judgeOrderMap.get("orderIsShopTake");
                    List<PayConsumeRecordDTO> payConsumeRecord = payConsumeRecordMapper.queryOrderNo(out_trade_no);
                    List<Integer> allRecordStatus = payConsumeRecordMapper.queryAllRecordStatus(out_trade_no);
                    BigDecimal money = new BigDecimal(0);
                    for (int i = 0; i < payConsumeRecord.size(); i++) {
                        money = money.add(payConsumeRecord.get(i).getRecordMoney());
                    }
                    if (allRecordStatus.contains(1)) {
                        String orderId = payConsumeRecord.get(0).getOrderId();
                        String userName = payConsumeRecord.get(0).getUserNickname();
                        String recordMoney = PayToolUtil.getMoney(money.toString());
                        if (out_trade_no.equals(orderId) && total_fee.equals(recordMoney)
                                && mch_id.equals(WXPayConfig.MCH_ID)) {
                            payConsumeTradeMapper.updateConsumeTradePaymentMoney(out_trade_no, 3);
                            Map<Object, Object> map = new HashMap<Object, Object>();
                            Integer payCode = 3;
                            // 待发货
                            Integer orderStatus = 3;
                            //判断是否是积分商品订单 扣除积分
                            updateUserJIfen(out_trade_no);
                            //门店订单 0 是 1 否
                            if (null != orderIsShopTake && 1 == orderIsShopTake) {
                                //如果是门店订单就将订单状态修改为 已发货
                                orderStatus = 4;
                            }
                            //虚拟订单 0 是 1 否
                            if (null != virtualGoods && 0 == virtualGoods) {
                                //如果是虚拟订单就将订单状态修改为 已发货
                                orderStatus = 4;
                            }
                            // 支付方式
                            Integer paymentId = 1;
                            // 支付方式名称
                            String paymentName = "在线支付";
                            // 支付时间
                            String paymentTime = DateUtils.getTime();
                            // 第三方支付号
                            String paymentOtherNumber = transaction_id;
                            String orderFrom = RedisUtil.get(YFConfig.FKGOU_ORDERFORM + out_trade_no);
                            map.put("payCode", payCode);
                            map.put("orderFrom", orderFrom);
                            map.put("paymentId", paymentId);
                            // 商户订单号
                            map.put("paymentNumber", out_trade_no);
                            map.put("orderStatus", orderStatus);
                            map.put("paymentName", paymentName);
                            map.put("paymentTime", paymentTime);
                            map.put("paymentOtherNumber", paymentOtherNumber);
                            boolean updatePayment = orderServiceClient.HFiveUpdateOrderBaseByPayment(map);
                            // 更改支付表状态ConsumeRecord
                            Integer recordStatus = 3;
                            Map<String, Object> recordMap = new HashMap<>();
                            recordMap.put("recordStatus", recordStatus);
                            recordMap.put("paymentTime", paymentTime);
                            recordMap.put("outTradeNo", out_trade_no);
                            boolean updateConsumeRecord = payConsumeRecordMapper.updateComsumeRecord(recordMap);
                            // 更改ConsumeTrade
                            Integer orderStateId = 3;
                            // 支付方式
                            Integer paymentChannelId = 4;
                            String closeTime = DateUtils.getTime();
                            boolean updateConsumeTrade = payConsumeTradeMapper.updateConsumeTrade(orderStateId, paymentTime,
                                    closeTime, out_trade_no, paymentChannelId);

                            // 库存传值
                            List<String> orderIdList = payConsumeRecordMapper.queryPayOrderId(orderId);
                            String orderList = Url.listToString2(orderIdList);
                            // 发送feign,提交下单通知
                            Map<String, Object> messageMap = new HashMap<String, Object>();
                            // 支付号
                            messageMap.put("orderId", out_trade_no);
                            messageMap.put("paymentTime", paymentTime);
                            // 发送下单通知
                            orderServiceClient.orderToInform(messageMap);
                            return_data.put("return_code", "SUCCESS");
                            return_data.put("return_msg", "OK");
                            return StringUtils.GetMapToXML(return_data);
                        } else {
                            log.info("订单号或订单金额不符！");
                            return_data.put("return_code", "FAIL");
                            return_data.put("return_msg", "订单号或订单金额不符！");
                            return StringUtils.GetMapToXML(return_data);
                        }
                    } else {
                        return_data.put("return_code", "SUCCESS");
                        return_data.put("return_msg", "OK");
                        return StringUtils.GetMapToXML(return_data);
                    }
                }
            }
        } catch (Exception e) {
            log.info("notifyWeiXinPayErrorResults:" + e.getMessage());
            // 回滚
            try {
                GlobalTransactionContext.reload(RootContext.getXID()).rollback();
            } catch (TransactionException e1) {
                return e1.getMessage().toString();
            }
            return e.getMessage().toString();
        }
    }

    /**
     * 获取微信网页code链接
     *
     */
    @Override
    public Map<String, Object> getCode(Map<String, String> paraMap) {
        String redirect_uri = paraMap.get("redirect_uri");
        //获取配置
        String paymentMode1 = "01";
        Map<String, Object> outMap1 = payConfigMapper.selectPayConfig(paymentMode1);
        WXPayConfig.GZ_APP_ID = outMap1.get("appID").toString();
        WXPayConfig.GZ_APP_SECRET = outMap1.get("appSecret").toString();
        Map<String, Object> result = new HashMap<String, Object>();
        // 第一步：用户同意授权，获取code
        String strUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + WXPayConfig.GZ_APP_ID +
                "&redirect_uri=" + redirect_uri +
                "&response_type=code" +
                "&scope=snsapi_base" +
                "&state=STATE#wechat_redirect";
        result.put("code","1");
        result.put("data",strUrl);
        result.put("desc","");
        return result;
    }

    /**
     * 获取微信网页OpenId
     *
     */
    @Override
    public Map<String, Object> getOpenId(Map<String, String> paraMap) {
        String code = paraMap.get("code");
        //获取配置
        String paymentMode1 = "01";
        Map<String, Object> outMap1 = payConfigMapper.selectPayConfig(paymentMode1);
        WXPayConfig.GZ_APP_ID = outMap1.get("appID").toString();
        WXPayConfig.GZ_APP_SECRET = outMap1.get("appSecret").toString();
        Map<String, Object> result = new HashMap<String, Object>();
        // 第一步：用户同意授权，获取code
        String strUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + WXPayConfig.GZ_APP_ID +
                "&secret=" + WXPayConfig.GZ_APP_SECRET + "&code=" + code + "&grant_type=authorization_code";
        String resultStr = RedisUtil.get(strUrl);
        resultStr = new String(resultStr.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
        JSONObject result1 = JSONObject.parseObject(resultStr);
        log.info("result1==={}", result1);
        String openid = result1.getString("openid");
        String session_key = result1.getString("session_key");
        result.put("openid", openid);
        result.put("session_key", session_key);
        result.put("code","1");
        result.put("data",openid);
        result.put("desc","");
        return result;
    }

    /**
     * 如果是积分订单就 修改用户积分
     */
    public void updateUserJIfen(String orderId) {
        Integer amountAotalIntegral = null;
        //积分商品 0  是  1 否
        Integer integralGoods = 1;
        //是纯数字
        QueryRecordParaDTO queryGoodsPara = null;
        if (PayToolUtil.isInteger(orderId)) {
            queryGoodsPara = payConsumeTradeMapper.queryRecordPriceAndName(orderId);
        } else {
            //不是纯数字
            queryGoodsPara = payConsumeTradeMapper.queryRecordPriceAndName(orderId);
        }
        if (null == queryGoodsPara) {
            return;
        }
        QueryGoodsParaDTO queryGoodsParaDTO2 = payConsumeTradeMapper.queryGoodsOrderAndUser(queryGoodsPara.getOrderId(), queryGoodsPara.getBuyerId());
        if (null == queryGoodsParaDTO2 && null != queryGoodsParaDTO2.getTotalIntegral()) {
            return;
        }
        //获取积分商品订单的积分
        Integer totalIntegral = queryGoodsParaDTO2.getTotalIntegral();
        //积分商品 0  是  1 否
        integralGoods = queryGoodsParaDTO2.getIntegralGoods();
        amountAotalIntegral = totalIntegral;
        if (null != integralGoods && integralGoods == 0) {
            //获取用户积分
            Integer userIntegral = usermsServiceClient.getMemberIntegralByUserId(queryGoodsPara.getBuyerId());
            if (null != userIntegral && amountAotalIntegral <= userIntegral) {
                //扣除积分
                //修改会员积分和会员等级
                MemberMessageListIntegralDTO updateMemberMessageListIntegral = new MemberMessageListIntegralDTO();
                ArrayList<String> list = new ArrayList<>();
                list.add(queryGoodsPara.getBuyerId());
                updateMemberMessageListIntegral.setUserIdList(list);
                updateMemberMessageListIntegral.setIntegral(amountAotalIntegral);
                //1是增加积分 0 是扣除积分
                updateMemberMessageListIntegral.setType(0);
                usermsServiceClient.updateMemberIntegral(updateMemberMessageListIntegral);
                //添加积分修改记录
                Map<String, Object> pointParam = new HashMap<>();
                pointParam.put("PointsLogType", CommonType.pointsLogType.CONSUME.getCode());
                pointParam.put("ClassId", CommonType.pointType.POINTS_EXCHANGE_VOUCHER.getCode());
                pointParam.put("PointsLogTime", DateUtils.getTime());
                pointParam.put("PointsLogDesc", CommonType.pointType.POINTS_EXCHANGE_GOODS.getDesc());
                pointParam.put("PointsLogFlag", "reg");
                pointParam.put("UserId", queryGoodsPara.getBuyerId());
                pointParam.put("PointsLogPoints", amountAotalIntegral);
                pointParam.put("PointsLogOperate", CommonType.pointType.POINTS_EXCHANGE_GOODS.getDesc());
                pointParam.put("OrderId", orderId);
                usermsServiceClient.insertPointLogByMap(pointParam);
            }
        }
    }

    /**
     * 微信小程序支付回调判断该订单是否是 虚拟 / 自提 订单 如果是 生成兑换码
     *
     * @param orderIdIsNum
     */
    public Map<String, Integer> virtualWxExchangeCode(Map<String, String> orderIdIsNum) {
        Integer virtualGoods = null;
        String orderId = null;
        String redeemCodeUrl = null;
        String code = null;
        Integer orderIsShopTake = null;
        Map<String, Integer> judgeOrderMap = new HashMap<>();
        try {
            ResponseResult res = orderServiceClient.isVirtualOrder(orderIdIsNum);
            Map<String, Object> map = (Map<String, Object>) res.getData();
            virtualGoods = (Integer) map.get("virtualGoods");
            orderId = (String) map.get("orderId");
            orderIsShopTake = (Integer) map.get("orderIsShopTake");
            //虚拟订单 0 是 1 否
            if (null != virtualGoods && 0 == virtualGoods || null != orderIsShopTake && 1 == orderIsShopTake) {
                SimpleDateFormat df = new SimpleDateFormat("ddHHmmss");
                String timeStamp = df.format(new Date());
                String temp = String.valueOf(Math.round((Math.random() + 1) * 1000));
                code = temp + timeStamp;
                ResponseResult resultResp = QrCodeUtil.GenerateQRCode(code);
                redeemCodeUrl = String.valueOf(thirdPartyServiceClient.uploadToOssBase64((OssUploadUpdateParamDTO) resultResp.getData()).getData());
                Map<String, Object> param = new HashMap<>();
                param.put("order", orderId);
                param.put("redeemCode", code);
                param.put("redeemCodeUrl", redeemCodeUrl);
                //为虚拟拟订单添加兑换码
                orderServiceClient.addRedeemCode(param);
            }

            judgeOrderMap.put("virtualGoods", virtualGoods);
            judgeOrderMap.put("orderIsShopTake", orderIsShopTake);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return judgeOrderMap;
    }

    @Override
    public String plusNotifyWeiXinPay(HttpServletRequest request, HttpServletResponse response) {
        log.info("------支付成功，进入回调lx------");
        log.info("------支付成功，进入回调notifyWeiXinPay------");
        try {
            InputStream inStream = request.getInputStream();
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            String resultxml = new String(outSteam.toByteArray(), "utf-8");
            log.info("resultxml:" + resultxml);
            @SuppressWarnings("unchecked")
            Map<String, String> params = PayCommonUtil.doXMLParse(resultxml);
            outSteam.close();
            inStream.close();
            Map<String, String> return_data = new HashMap<String, String>();
            if (!PayCommonUtil.isTenpaySign(params)) {
                // 支付失败
                log.info("------支付失败------");
                return_data.put("return_code", "FAIL");
                return_data.put("return_msg", "return_code不正确");
                log.info("return_data：" + StringUtils.GetMapToXML(return_data));
                return StringUtils.GetMapToXML(return_data);
            } else {
                log.info("===============付款成功==============");

                String out_trade_no = params.get("out_trade_no");
                log.info("-----out_trade_no-----" + out_trade_no);
                String attach = params.get("attach");
                Map map1 = JsonUtils.string2Obj(attach, Map.class);
                // 获取wx传来的订单价格
                String total_fee = params.get("total_fee");
                log.info("-----total_fee-----" + total_fee);
                // 微信支付分配的商户号
                String mch_id = params.get("mch_id");
                log.info("-----mch_id-----" + mch_id);
                // 微信支付订单号
                String transaction_id = params.get("transaction_id");
                log.info("-----transaction_id-----" + transaction_id);

                // 更改销量
                List<WapGoodsSaleSumDTO> wapGood = payUserResourceMapper.queryGoodsByOrderId(out_trade_no);
                goodServiceClient.updateGoodsSalenum(wapGood);

                //插入plus会员信息
                map1.put("plusOrder",out_trade_no);
                map1.put("type",3);
                ResponseResult plusmemberopen = usermsServiceClient.plusmemberopen(map1);
                if (plusmemberopen.getCode() == 1 || plusmemberopen.getCode() == 3){
                    // 结果已处理，返回success
                    return_data.put("return_code", "SUCCESS");
                    return_data.put("return_msg", "OK");
                    return StringUtils.GetMapToXML(return_data);
                }else{
                    return_data.put("return_code", "FAIL");
                    return_data.put("return_msg", "开通失败");
                    return StringUtils.GetMapToXML(return_data);
                }

            }
        } catch (Exception e) {
            log.info("notifyWeiXinPayErrorResults:" + e.getMessage());
        }
        return "OK";
    }

    @Override
    public ResponseResult queryWxPayStatus(Map<Object, Object> map) {
        ResponseResult rr = new ResponseResult();
        String token = (String) map.get("token");
        boolean isExistToken = RedisUtil.exists(YFConfig.YF_USER_TOKEN_USER + token);
        if (isExistToken) {
            try {
                UserInfoVO ui = ParseTokenUtils.getUserInfoByToken(token);
                String userId = ui.getUserId();
                String orderId = (String) map.get("orderId");
                if (PayToolUtil.isInteger(orderId)) {
                    // 纯数字订单
                    Integer status = payConsumeTradeMapper.queryStatusByInteger(orderId, userId);
                    if (null != status && status == 1) {
                        //状态未更改成功！
                        return ResponseResult.fail(BizCodeEnume.UPDATE_ERROR);
                    } else {
                        //状态更改成功！
                        return ResponseResult.success(BizCodeEnume.UPDATE_SUCCEEDED);
                    }
                } else {
                    List<Integer> status = payConsumeRecordMapper.queryStatus(orderId, userId);
                    if (!CollectionUtils.isEmpty(status)) {
                        for (Integer integer : status) {
                            if (integer == 1) {
                                //状态未更改成功！
                                return ResponseResult.fail(BizCodeEnume.UPDATE_ERROR);
                            } else {
                                //状态更改成功！
                                return ResponseResult.success(BizCodeEnume.UPDATE_SUCCEEDED);
                            }
                        }
                    }
                    return ResponseResult.fail(BizCodeEnume.NO_INFORMATION_OBTAINED);
                }
            } catch (Exception e) {
                return ResponseResult.fail(e.getMessage());
            }
        } else {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
    }

    @Override
    public ResponseResult queryWxPayplus(Map<Object, Object> map) {
        ResponseResult rr = new ResponseResult();
        String token = (String) map.get("token");
        boolean isExistToken = RedisUtil.exists(YFConfig.YF_USER_TOKEN_USER + token);
        if (isExistToken) {
            UserInfoVO ui = ParseTokenUtils.getUserInfoByToken(token);
            String userId = ui.getUserId();
            String plusOrder = String.valueOf(map.get("plusOrder"));
            Integer queryplusorder = payConsumeRecordMapper.queryplusorder(userId, plusOrder);
            if (queryplusorder == 1){
               return ResponseResult.success(BizCodeEnume.PAYMENT_SUCCESSFUL.getMsg());
            }else{
               return ResponseResult.success(BizCodeEnume.PAYMENT_FAILED.getMsg());
            }
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
    }
}
